const express = require("express");
const router = express.Router();

const { Setting } = require("../../models");

const { NotFoundError, success, failure } = require("../../utils/response");

// 系统设置象详情
router.get("/", async function (req, res) {
  try {
    // findByPk, 通过主键查找，primary key 【pk】
    const setting = await getSetting();
    success(res, "查询系统设置成功", { setting });
  } catch (err) {
    failure(res, err);
  }
});
/**
 * 更新系统设置
 */
router.put("/", async function (req, res) {
  try {
    const setting = await getSetting();

    await setting.update(filterBody(req));
    success(res, "系统设置更新成功", setting);
  } catch (error) {
    failure(res, error);
  }
});

function filterBody(req) {
  return {
    name: req.body.name,
    icp: req.body.icp,
    copyright: req.body.copyright,
  };
}

// 公共方法，查找系统设置
async function getSetting() {
  const setting = await Setting.findOne();

  if (!setting) {
    // 抛出异常，让trycatch捕获
    throw new NotFoundError(`系统设置未找到`);
  }

  return setting;
}

module.exports = router;
